from PySide6.QtWidgets import * # type: ignore
from PySide6.QtCore import * # type: ignore
from PySide6.QtGui import * # type: ignore
from qfluentwidgets import * # type: ignore

from utils import cfg_util, font_util

class FontSetterCard(QWidget):
    '''Widget for selecting application font from available system fonts'''
    
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # List widget to display available fonts
        self.selection_list = ListWidget(self)
        self.selection_list.itemSelectionChanged.connect(self.saveFontSelection)

        # Create list items for each available font
        self.items: list[QListWidgetItem] = []
        for font in font_util.getFonts():
            item = QListWidgetItem()
            item.setFont(QFont(font, 14))  # Show font preview
            item.setText(font)
            self.items.append(item)

        # Add all font items to the list
        for item in self.items:
            self.selection_list.addItem(item)

        self.selection_list.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
        layout.addWidget(self.selection_list)
        self.setLayout(layout)

    def saveFontSelection(self) -> None:
        '''Save selected font to configuration'''
        if not self.selection_list.currentItem():
            self.updateSelection()  # Reset if no selection
            return
        cfg_util.config_instance.font = self.selection_list.currentItem().text()
        cfg_util.saveConfig()

    def updateSelection(self) -> None:
        '''Update list selection to match current configuration'''
        current_font = cfg_util.config_instance.font
        for item in self.items:
            if item.text() == current_font:
                item.setSelected(True)  # Select current font
                # Scroll to make selected item visible
                self.selection_list.scrollToItem(item, QAbstractItemView.ScrollHint.PositionAtCenter)
                return